package com.jz.community.basecomm.base;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.jz.community.basecomm.mvp.BaseMvpPresenter;
import com.jz.community.basecomm.routerUtils.RouterCommonUtils;
import com.jz.community.basecomm.routerUtils.RouterIntentConstant;
import com.jz.community.basecomm.utils.RxImageDownload;
import com.jz.community.basecomm.utils.SHelper;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecommunity.R;
import com.jz.community.basecommunity.R2;
import com.orhanobut.logger.Logger;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.SslError;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.utils.TbsLog;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

public class BaseX5WebActivity extends BaseMvpActivity {


    @BindView(R2.id.web_back)
    ImageView webBack;
    @BindView(R2.id.web_title)
    public TextView webTitle;
    @BindView(R2.id.web_share)
    TextView webShare;
    @BindView(R2.id.web_toolbar)
    Toolbar webToolbar;
    @BindView(R2.id.progressBar)
    ProgressBar progressBar;
    @BindView(R2.id.x5_web)
    public WebView x5Web;

    public CompositeDisposable compositeDisposable;

    public String mUrl;
    public String mTitle;

    public int canShare = 0; //0 无分享 1 有分享

    //分享链接
    public String shareUrl = "";
    //分享标题
    public String shareTitle = "";
    //分享内容
    public String shareDesc = "";
    //分享图片
    public String shareImg = "";

    private ValueCallback<Uri> mUploadMessage;
    private android.webkit.ValueCallback<Uri[]> mUploadCallbackAboveL;

    private static final int FILECHOOSER_RESULTCODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.activity_base_x5_web;
    }

    @Override
    protected BaseMvpPresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView() {
        super.initView();
        setImmersionBar(webToolbar);
        getDataByBundle();
        addWebViewListener();

        x5Web.setWebViewClient(new tbsWebClient());
        x5Web.loadUrl(mUrl);
    }

    /**
     * 获取getIntent附带数据
     */
    private void getDataByBundle() {
        Intent intent = getIntent();
        if (intent.hasExtra("title")) {
            mTitle = intent.getStringExtra("title");
            webTitle.setText(mTitle);
        } else {
            webTitle.setText("社区人");
        }

        if (intent.hasExtra("url")) {
            mUrl = intent.getStringExtra("url");
        } else {
            x5Web.setVisibility(View.INVISIBLE);
        }

        if (intent.hasExtra("canShare")) {
            canShare = 1;
            webShare.setVisibility(View.VISIBLE);

            if (intent.hasExtra("share_url")) {
                shareUrl = intent.getStringExtra("share_url");
            }

            if (intent.hasExtra("share_title")) {
                shareTitle = intent.getStringExtra("share_title");
            }

            if (intent.hasExtra("share_desc")) {
                shareDesc = intent.getStringExtra("share_desc");
            }

            if (intent.hasExtra("share_img")) {
                shareImg = intent.getStringExtra("share_img");
            }

        } else {
            canShare = 0;
            webShare.setVisibility(View.GONE);
        }
    }

    private void addDisposable(Disposable disposable) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
    }

    private void dispose() {
        if (compositeDisposable != null) {
            compositeDisposable.dispose();
        }
    }

    private void addWebViewListener() {
        new BaseX5WebSetting().setBaseWebview(mActivity, x5Web);
        x5Web.addJavascriptInterface(this, JSActionInterface.JSACTION_PRFIX);

        //设置先加载网络数据再加载图片
        x5Web.getSettings().setLoadsImagesAutomatically(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            x5Web.getSettings().setAllowUniversalAccessFromFileURLs(true);
        }

        x5Web.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int progress) {
                super.onProgressChanged(webView, progress);
                progressBar.setProgress(progress);
                if (progress == 80) {
                    SHelper.gone(progressBar);
                }
            }

            @Override
            public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
                                       JsResult arg3) {
                return super.onJsConfirm(arg0, arg1, arg2, arg3);
            }

            @Override
            public boolean onJsAlert(WebView arg0, String arg1, String arg2,
                                     JsResult arg3) {
                /**
                 * 这里写入你自定义的window alert
                 */
                return super.onJsAlert(null, arg1, arg2, arg3);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                }
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("*/*");
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                }
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
                i.setType(type);
                startActivityForResult(Intent.createChooser(i, "File Chooser"),
                        FILECHOOSER_RESULTCODE);
            }

            // For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                }
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                String type = TextUtils.isEmpty(acceptType) ? "*/*" : acceptType;
                i.setType(type);
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
            }

            //Android 5.0+
            @Override
            @SuppressLint("NewApi")
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                if (mUploadMessage != null) {
                    mUploadMessage.onReceiveValue(null);
                }
                mUploadCallbackAboveL = filePathCallback;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                if (fileChooserParams != null && fileChooserParams.getAcceptTypes() != null
                        && fileChooserParams.getAcceptTypes().length > 0) {
                    i.setType(fileChooserParams.getAcceptTypes()[0]);
                } else {
                    i.setType("*/*");
                }
                startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
                return true;
            }

        });

        x5Web.setOnLongClickListener(v -> {
            final WebView.HitTestResult hitTestResult = x5Web.getHitTestResult();
            // 如果是图片类型或者是带有图片链接的类型
            if (hitTestResult.getType() == android.webkit.WebView.HitTestResult.IMAGE_TYPE ||
                    hitTestResult.getType() == android.webkit.WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                // 弹出保存图片的对话框
                // 获取到图片地址后做相应的处理
                //获取图片链接
                String picUrl = hitTestResult.getExtra();
                showNormalDialog(picUrl);

                return true;
            }
            return false;//保持长按可以复制文字
        });

        x5Web.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK
                        && x5Web.canGoBack()) {
                    x5Web.goBack();
                    return true;
                }
                return false;
            }
        });
    }

    private void showNormalDialog(String picUrl) {
        new MaterialDialog.Builder(mActivity)
                .title("提示")
                .content("是否保存图片？")
                .positiveText("保存")
                .negativeText("取消")
                .negativeColor(ContextCompat.getColor(BaseX5WebActivity.this, R.color.negative_color))
                .positiveColor(ContextCompat.getColor(BaseX5WebActivity.this, R.color.positive_color))
                .onPositive((dialog, which) -> new Thread(() -> {
                    BaseX5WebActivity.this.saveImage(picUrl);
                }).start())
                .onNegative((dialog, which) -> dialog.dismiss())
                .show();
    }

    public void saveImage(String imgUrl) {
        Disposable d = RxImageDownload.saveImageAndGetPath(mActivity, imgUrl, System.currentTimeMillis() + "")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(uri -> {
                    File appDir = new File(Environment.getExternalStorageDirectory(), mActivity.getResources().getString(R.string.app_name));
                    String msg = String.format("图片已保存至 %s 文件夹", appDir.getAbsoluteFile());
                    WpToast.s(mActivity, msg);
                });
        addDisposable(d);

    }

    class tbsWebClient extends WebViewClient {

        /**
         * 加载过程中 拦截加载的地址url
         *
         * @param webView
         * @param s       被拦截的url
         * @return
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView webView, String s) {
            Logger.e("TBSWebView ", "shouldOverrideUrlLoading " + s);
            if (s != null) {
                if (s.endsWith(".apk")) {
                    startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri
                            .parse(s)));
                } else {
                    webView.loadUrl(s);
                }

            }
            return false;
        }

        /**
         * 页面加载过程中，加载资源回调的方法
         *
         * @param webView
         * @param s
         */
        @Override
        public void onLoadResource(WebView webView, String s) {
            super.onLoadResource(webView, s);
        }

        /**
         * 页面开始加载调用的方法
         *
         * @param webView
         * @param s
         * @param bitmap
         */
        @Override
        public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
            super.onPageStarted(webView, s, bitmap);

        }

        /**
         * 页面加载完成回调的方法
         *
         * @param webView
         * @param s
         */
        @Override
        public void onPageFinished(WebView webView, String s) {
            super.onPageFinished(webView, s);
            // 关闭图片加载阻塞
            if (!webView.getSettings().getLoadsImagesAutomatically()) {
                webView.getSettings().setLoadsImagesAutomatically(true);
            }
            if (progressBar != null) {
                progressBar.setVisibility(View.GONE);
            }
        }

        @Override
        public void onScaleChanged(WebView webView, float v, float v1) {
            super.onScaleChanged(webView, v, v1);
            if (x5Web != null) {
                x5Web.requestFocus();
                x5Web.requestFocusFromTouch();
            }
        }

        @Override
        public void onReceivedError(WebView webView, int i, String s, String s1) {
            super.onReceivedError(webView, i, s, s1);
            //出现页面错误的时候，不让webView显示了。同时跳出一个错误Toast
            x5Web.setVisibility(View.INVISIBLE);
            WpToast.s(mActivity, "请检查您的网络设置");
            Logger.e("网页加载失败");
        }

        @Override
        public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, SslError sslError) {
            super.onReceivedSslError(webView, sslErrorHandler, sslError);
            sslErrorHandler.proceed();//接受证书
        }
    }

    /**
     * 网页分享
     */
    public void shareWeb() {

    }


    /**
     * 分享有礼js
     */
    @JavascriptInterface
    public void qrCcode(final String url) {
        //跳转分享有礼
        runOnUiThread(() -> RouterCommonUtils.startParameterActivity(RouterIntentConstant.SHARE_GIFT, "url", url));
    }

    @OnClick(R2.id.web_back)
    public void backClick() {
        setResult(RESULT_OK);
        finish();
    }

    @OnClick(R2.id.web_share)
    public void shareClick() {
        if (canShare == 1) {
            //可以分享
            shareWeb();
        }
    }

    @Override
    public void onBackPressedSupport() {
        //这里不要继承
        if (x5Web != null && x5Web.canGoBack()) {
            x5Web.goBack();
        } else {
            finish();
        }
    }

    @Override
    protected void onPause() {
        if (x5Web != null) {
            x5Web.onPause();
        }
        super.onPause();
    }


    @Override
    protected void onResume() {
        if (x5Web != null) {
            x5Web.onResume();
        }
        super.onResume();

    }


    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && x5Web.canGoBack()) {
            x5Web.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (x5Web != null) {
            x5Web.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            x5Web.clearHistory();

            ((ViewGroup) x5Web.getParent()).removeView(x5Web);
            x5Web.destroy();
            x5Web = null;
        }
        super.onDestroy();
        dispose();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        TbsLog.d("TAG", "onActivityResult, requestCode:" + requestCode
                + ",resultCode:" + resultCode);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != mUploadMessage) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        mUploadMessage.onReceiveValue(result);
                        mUploadMessage = null;
                    }
                    if (null != mUploadCallbackAboveL) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        Uri[] uris = new Uri[]{result};
                        mUploadCallbackAboveL.onReceiveValue(uris);
                        mUploadCallbackAboveL = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != mUploadMessage) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
            if (null != mUploadCallbackAboveL) {
                mUploadCallbackAboveL.onReceiveValue(null);
                mUploadCallbackAboveL = null;
            }

        }

    }
}
